<template>
  <div class="switchBox">
    <div :class="['switch', value ? 'open' : 'close']" @click="toggle">
      <span class="text">{{ value ? '是' : '否' }}</span>
    </div>
    <p v-if="title" class="title">{{ title }}</p>
  </div>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      default: ''
    },
    defaultVal: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      value: this.defaultVal
    }
  },
  methods: {
    toggle() {
      const vm = this
      vm.value = !vm.value
    }
  }
}
</script>

<style lang="scss" scoped>
.switchBox {
  .switch {
    width: 44px;
    height: 22px;
    background-color: #1aca61;
    border-radius: 16px;
    line-height: 22px;
    position: relative;
    cursor: pointer;
    transition: all 0.3s;
    user-select: none;
    &.close {
      opacity: 0.3;
      .text {
        right: 10px;
      }
      &:after {
        left: 2px;
      }
    }
    &.open {
      .text {
        left: 10px;
      }
      &:after {
        left: 24px;
      }
    }
    &:after {
      content: '';
      width: 18px;
      height: 18px;
      background-color: #fff;
      position: absolute;
      top: 2px;
      border-radius: 50%;
      transition: left 0.1s;
    }
    .text {
      position: absolute;
      font-size: 12px;
    }
  }
  .title {
    text-align: center;
    margin-top: 6px;
    font-size: 12px;
  }
}
</style>
